<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total"
                :delFunc="handleDelete" :changePage="changePage" :change-page-size="changePageSize" :currentPage="page.page" :pageSize="page.page_size">
                <template #status="{rows}">
                    <el-tag v-if="rows.status == -1" type="danger">驳回</el-tag>
                    <el-tag v-else-if="rows.status == 0" type="warning">待审批</el-tag>
                    <el-tag v-else-if="rows.status == 1" type="info">审批通过</el-tag>
                    <el-tag v-else type="success">已到账</el-tag>
                </template>
                <template #out_trade_no="{rows}">
                    <el-button type="primary" link @click="gotoDetail(rows)">{{rows.out_trade_no}}</el-button>
                </template>
                <template #operator="{rows}">
                    <!-- :disabled="(rows.o_glasses_num - rows.num) == 0" -->
                    <el-button :disabled="rows.status != 0" type="warning" @click="backMoney(rows)" >{{rows.status == 0 ? '退款' : '已退款'}}</el-button>
                </template>
            </TableCustom>

        </div>
        <el-dialog
                v-model="dialogVisible"
                title="退款操作"
                width="500"
            >
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="auto"
                    :size="formSize"
                    status-icon
                >
                    <el-form-item label="退款原因" prop="refund_reason">
                        <el-input type="textarea" v-model="ruleForm.refund_reason" />
                    </el-form-item>
                    <el-form-item label="眼镜数量" prop="refund_num">
                        <el-input-number v-model="ruleForm.refund_num" :min="0" :max="MaxNum"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                        <el-button type="primary" @click="conformBackMoney(ruleFormRef)">确认</el-button>
                        </el-form-item>
                    </el-form>
            </el-dialog>
    </div>
</template>

<script setup lang="ts" name="collaborativeAdministrator-user">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, RefreshLeft } from '@element-plus/icons-vue';
import { User } from './types/cooperUser';
import { payment_wait_refund, hand_refund } from '@/api';
import TableCustom from '@/components/table-custom.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import { useRouter } from 'vue-router';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const router = useRouter();
//  跳转详情
const gotoDetail = (row) => {
    router.push({
        name: 'galssOrder-orderInfoDetail',
        query: {o_order_code: row.out_trade_no},
    })
}
const getNowTime = () => {
    return `${new Date().getFullYear()}-${(new Date().getMonth() + 1) > 9 ? (new Date().getMonth() + 1) : '0' + (new Date().getMonth() + 1)}-${new Date().getDate() > 9 ? new Date().getDate() : '0' + new Date().getDate()}`
}
// 查询相关
const query = reactive({
    data_time: [getNowTime(), getNowTime()],
    o_order_code: null,
    status: null,
    user_telphone: null,
    // o_pay_status: null,
    // area: '',
});
// 查询条件相关
const searchOpt = ref<FormOptionList[]>([
    // { type: 'area', label: '行政区划：', prop: 'area', placeholder: '请选择行政区划'},
    { type: 'daterange', label: '查询时间：', prop: 'data_time', placeholder: '请选择时间范围', format: 'YYYY-MM-DD'},
    { type: 'input', label: '订单编号:', prop: 'o_order_code', placeholder: '请输入订单编号' },
    { type: 'input', label: '租户手机号码:', prop: 'user_telphone', placeholder: '请输入租户手机号码' },
    { type: 'select', label: '订单状态:', prop: 'status', placeholder: '请输入订单状态', opts: [{value: 0, label: "待审批"},  {value: 1, label: "审批通过"}, {value: -1, label: "驳回"},  {value: 2, label: "已到账"}] },
    // { type: 'select', label: '支付状态:', prop: 'o_pay_status', placeholder: '请输入支付状态', opts: [{value: 0, label: "未支付"},  {value: 1, label: "已支付"}] }
])
const handleSearch = () => {
    console.log(query)
    changePage(1);
};

// 押金返还
const MaxNum = ref(1)
interface RuleForm {
    o_order_code: string,
    refund_num: number,
    refund_reason: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    o_order_code:'',
    refund_num: 0,
    refund_reason: '正常退款',
})

const rules = reactive<FormRules<RuleForm>>({
    refund_reason: [
        { required: true, message: '请输入退款原因', trigger: 'blur' },
    ],
    refund_num:[
        { required: true, message: '请输入退款的眼镜数量', trigger: 'change' },
    ],
})

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}
const dialogVisible = ref(false)
const tempObj = ref({o_is_refund: 0})
const backMoney = (data) => {
    console.log(data)
    tempObj.value = data
    ruleForm.refund_num = Number(data.num - data.f_num)
    ruleForm.o_order_code = data.out_trade_no
    ruleForm.refund_reason = '正常退款'
    MaxNum.value = Number(data.num - data.f_num)
    dialogVisible.value = true
}

const conformBackMoney = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
           ElMessageBox.confirm('确认要退款？', '提示').then(() => {
                hand_refund({...ruleForm}).then(res => {
                    if(res.code == '1000') {
                        ElMessage({
                            type: 'success',
                            message: '退款申请成功',
                        })
                        tempObj.value.status = 0
                        resetForm(formEl)
                    } else {
                        ElMessage({
                            type: 'error',
                            message: res.msg,
                        })
                    }
                    
                })
            }).catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消退款',
                })
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}


// 表格相关
let columns = ref([
    { prop: 'user_telphone', label: '租户名称' },
    { prop: 'out_trade_no', label: '订单号' },
    { prop: 'out_refund_no', label: '退款单号' },
    { prop: 'total_fee', label: '订单金额' },
    { prop: 'refund_fee', label: '退款金额' },
    { prop: 'withdrawal_code', label: '申请单编号' },
    { prop: 'update_time', label: '更新时间' },
    { prop: 'create_time', label: '申请时间' },
    { prop: 'status', label: '订单状态' },
    { prop: 'operator', label: '操作', width: 250 },
])
const page = reactive({
    page: 1,
    page_size: 10,
    total: 0,
})
const tableData = ref<User[]>([]);
const getData = async () => {
    const res = await payment_wait_refund({page: page.page, page_size: page.page_size, ...query})
    tableData.value = res.data.data_list;
    page.total = res.data.total;
};
getData();

const changePage = (val: number) => {
    console.log(val)
    page.page = val;
    getData();
};

const changePageSize = (val: number) => {
    page.page_size = val;
    getData();
};


// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '150px',
    span: 20,
    list: [
        { type: 'select', label: '上级合作管理员', prop: 'c_superior_code', required: false, placeholder: '请选择上级合作管理员' },
        { type: 'input', label: '合作管理员名称', prop: 'c_user_name', required: true, placeholder: '请输入合作管理员名称' },
        { type: 'input', label: '联系人姓名', prop: 'c_contacts_name', required: true, placeholder: '请输入联系人姓名' },
        { type: 'input', label: '联系人电话', prop: 'c_contacts_phone', required: true, placeholder: '请输入联系人电话' },
        { type: 'input', label: '联系人地址', prop: 'c_contacts_area', required: true, placeholder: '请输入联系人地址' },
        
        { type: 'custom_area', label: '行政区划', prop: 'custom_area', required: true, placeholder: '请选择行政区划' },
        { type: 'select', label: '所属银行', prop: 'c_bank_name', required: false, placeholder: '请选择所属银行' },
        { type: 'input', label: '结算账户', prop: 'c_bank_account', required: false, placeholder: '请输入合作结算账户' },
        { type: 'input', label: '结算账号', prop: 'c_bank_code', required: false, placeholder: '请输入结算账号' },
        { type: 'input', label: '支行名称', prop: 'c_bank_real_name', required: false, placeholder: '请输入支行名称' },
        { type: 'textarea', label: '备注', prop: 'c_remarks', required: false, placeholder: '请输入备注' },
    ]
})
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = (row: User) => {
    row.custom_area = [`${row.c_province}`, `${row.c_city}`, `${row.c_area}`];
    rowData.value = { ...row };
    isEdit.value = true;
    visible.value = true;
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};


// 删除相关
const handleDelete = (row: User) => {
    ElMessageBox.confirm('确定要删除吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
        })
        .catch(() => { });
    
}

const cancelOrder = (row: User) =>  {
    ElMessageBox.confirm('确定要审核订单吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
            // cancel_order({o_order_code: row.o_order_code }).then(res => {
            //     if (res.code == '1000') {
            //         getData();
            //         ElMessage.success('取消成功');
            //     }
            // })
        })
        .catch(() => { });
}
</script>

<style scoped></style>